import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_scan_tool/bloc/device/device_bloc.dart';
import 'package:flutter_scan_tool/bloc/tool/tool_bloc.dart';
import 'package:flutter_scan_tool/bloc/tool/tool_event.dart';
import 'package:flutter_scan_tool/models/antenna_info.dart';
import 'package:flutter_scan_tool/models/app_theme.dart';
import 'package:flutter_scan_tool/models/storage_info.dart';
import 'package:flutter_scan_tool/models/tool_kit.dart';
import 'package:flutter_scan_tool/utils/flash_helper.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../db/api_provider.dart';

class StorageView extends StatefulWidget {
  const StorageView({Key? key}) : super(key: key);

  @override
  State<StorageView> createState() => _StorageViewState();
}

class _StorageViewState extends State<StorageView>
    with TickerProviderStateMixin, WidgetsBindingObserver {
  AnimationController? bottomAnimationController;
  StorageInfo? storageInfo;
  List<ToolKit> list = [];
  final String STORAGE = "storage";

  @override
  void initState() {
    getStorageInfo();
    bottomAnimationController = AnimationController(
        duration: const Duration(milliseconds: 300), vsync: this);
    super.initState();
  }

  List<StorageInfo> storageAllList = [];
  List<StorageInfo> storageList = [];
  void getStorageInfo() async {
    SharedPreferences spf = await SharedPreferences.getInstance();
    String val = spf.getString(STORAGE) ?? '';
    if (val != '') {
      storageInfo = StorageInfo.fromJson(val);
    }

    try {
      List<StorageInfo> storageTemp = await ApiProvider.getStorageList();
      if (!mounted) {
        return;
      }

      setState(() {
        storageList = storageTemp;
        if (storageInfo != null) {
          selectStorage = storageInfo?.storageName ?? '';
          List<ToolKit> tempToolKit = storageInfo?.toolKitList ?? [];
          int count = storageList
              .where((element) => element.storageName == selectStorage)
              .length;
          if (count > 0) {
            toolKitList = storageList
                    .firstWhere(
                        (element) => element.storageName == selectStorage)
                    .toolKitList ??
                [];
            for (var item in storageInfo!.toolKitList ?? []) {
              selectToolKitList.add(item);
            }
            selectToolKit = tempToolKit.map((e) => e.toolKitName).toList();
            for (var item in selectToolKitList) {
              List<String> antennaTemp =
                  item.antennaList.map((e) => e.antennaPort).toList();
              antennaMap[item.toolKitName] = antennaTemp;
              gpiMap[item.toolKitName] = item.gpi;
              gpoMap[item.toolKitName] = item.gpo;
            }
          }
        }
      });
    } catch (err) {
      debugPrint(err.toString());
      if (mounted) {
        FlashHelper.toast(context, '仓储数据获取失败', MessageType.alert);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Stack(
        alignment: Alignment.bottomCenter,
        children: [
          Container(
            height: MediaQuery.of(context).size.height * 0.8,
            width: MediaQuery.of(context).size.width * 0.85,
            decoration: BoxDecoration(
              shape: BoxShape.rectangle,
              borderRadius: const BorderRadius.all(Radius.circular(20)),
              color: AppTheme.appTheme.cardBackgroundColor(),
            ),
            child: Column(
              children: <Widget>[
                const SizedBox(
                  height: 10,
                ),
                Container(
                  alignment: Alignment.centerLeft,
                  margin: const EdgeInsets.only(left: 18, top: 8),
                  child: Text(
                    '仓库名称',
                    style: AppTheme.appTheme.headline1(
                      fontWeight: FontWeight.w100,
                      fontSize: 18,
                    ),
                  ),
                ),
                storageListView(storageList),
                Container(
                  alignment: Alignment.centerLeft,
                  margin: const EdgeInsets.only(left: 18, top: 8),
                  child: Text(
                    '工具柜名称',
                    style: AppTheme.appTheme
                        .headline1(fontWeight: FontWeight.w100, fontSize: 18),
                  ),
                ),
                toolKitView(toolKitList),
                Container(
                  alignment: Alignment.centerLeft,
                  margin: const EdgeInsets.only(left: 18, top: 8),
                  child: Text(
                    '已选择的工具柜',
                    style: AppTheme.appTheme
                        .headline1(fontWeight: FontWeight.w100, fontSize: 18),
                  ),
                ),
                toolKitSelectView(selectToolKitList),
                Container(
                  alignment: Alignment.centerLeft,
                  margin: const EdgeInsets.only(left: 18, top: 8),
                  child: Text(
                    '工具柜对应的射频端口',
                    style: AppTheme.appTheme
                        .headline1(fontWeight: FontWeight.w100, fontSize: 18),
                  ),
                ),
                antennaSelectView(antennaPortList),
                Container(
                  alignment: Alignment.centerLeft,
                  margin: const EdgeInsets.only(left: 18, top: 8),
                  child: Text(
                    '工具柜对应GPO',
                    style: AppTheme.appTheme
                        .headline1(fontWeight: FontWeight.w100, fontSize: 18),
                  ),
                ),
                gpoSelectView(gpoList),
                Container(
                  alignment: Alignment.centerLeft,
                  margin: const EdgeInsets.only(left: 18, top: 8),
                  child: Text(
                    '工具柜对应GPI',
                    style: AppTheme.appTheme
                        .headline1(fontWeight: FontWeight.w100, fontSize: 18),
                  ),
                ),
                gpiSelectView(gpoList),
                SizedBox(
                  height: 40,
                  child: GestureDetector(
                    onTap: () async {
                      if (selectStorage == '') {
                        FlashHelper.toast(
                            context, '请选择仓库名称', MessageType.alert);
                        return;
                      }
                      if (selectToolKit.isEmpty) {
                        FlashHelper.toast(
                            context, '请选择工具柜名称', MessageType.alert);
                        return;
                      }
                      if (antennaMap.keys.isEmpty) {
                        FlashHelper.toast(
                            context, '请选择工具柜对应的天线号', MessageType.alert);
                        return;
                      }
                      if (antennaMap.keys.length < selectToolKit.length) {
                        FlashHelper.toast(
                            context, '天线号和工具柜的数量无法对应', MessageType.alert);
                        return;
                      }
                      if (gpoMap.keys.isEmpty) {
                        FlashHelper.toast(
                            context, '请选择工具柜对应的GPO', MessageType.alert);
                        return;
                      }
                      if (gpoMap.keys.length < selectToolKit.length) {
                        FlashHelper.toast(
                            context, 'GPO和工具柜的数量无法对应', MessageType.alert);
                        return;
                      }
                      if (gpiMap.keys.length < selectToolKit.length) {
                        FlashHelper.toast(
                            context, 'GPI和工具柜的数量无法对应', MessageType.alert);
                        return;
                      }
                      List<ToolKit> toolKitsList = [];
                      StorageInfo storageItem = storageList.firstWhere(
                          (element) => element.storageName == selectStorage);
                      for (var element in selectToolKit) {
                        ToolKit toolKitItem = toolKitList
                            .firstWhere((el) => el.toolKitName == element);
                        List<AntennaInfo> antennaInfoItemList = [];
                        List<String> antennaItemList = antennaMap[element]!;
                        for (var ele in antennaItemList) {
                          antennaInfoItemList.add(AntennaInfo(
                              id: ele,
                              toolKitId: toolKitItem.id,
                              antennaPort: ele));
                        }
                        ToolKit toolKit = ToolKit(
                            id: toolKitItem.id,
                            toolKitName: element,
                            storageId: storageItem.id,
                            gpo: gpoMap[element] ?? 0,
                            gpi: gpiMap[element] ?? 0,
                            antennaList: antennaInfoItemList);
                        toolKitsList.add(toolKit);
                      }
                      StorageInfo storageInfo = StorageInfo(
                          id: storageItem.id,
                          storageName: storageItem.storageName,
                          toolKitList: toolKitsList);
                      SharedPreferences spf =
                          await SharedPreferences.getInstance();
                      spf.setString(STORAGE, storageInfo.toJson());
                      debugPrint(storageInfo.toJson());
                      FlashHelper.toast(context, '保存成功', MessageType.message);
                      context.read<DeviceBloc>().add(DeviceStorageEvent(storageInfo));
                      context.read<ToolBloc>().add(ToolLoadEvent({}));
                      Navigator.of(context).pop();
                    },
                    child: const Icon(
                      Icons.done,
                      size: 35,
                      color: Colors.red,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  String selectStorage = '';
  List<ToolKit> selectToolKitList = [];
  List<int> gpoList = [1, 2, 3, 4,5,6,7,8];
  List<int> antennaPortList = [
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10,
    11,
    12,
    13,
    14,
    15,
    16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32
  ];

  Map<String, List<String>> antennaMap = {};
  Widget storageListView(List<StorageInfo> keyValueList) {
    return Container(
      margin: const EdgeInsets.only(top: 6),
      height: 48,
      child: ListView.builder(
        padding: const EdgeInsets.only(left: 16, right: 16, bottom: 8),
        itemBuilder: (context, index) {
          String storageId = keyValueList[index].id;
          String storageName = keyValueList[index].storageName;
          return GestureDetector(
            onTap: () {
              setState(() {
                toolKitList = [];
                selectToolKit.clear();
                selectToolKitList.clear();
                antennaMap.clear();
                tempList.clear();
                selectStorage = storageName;
                StorageInfo tempInfo = storageList
                    .firstWhere((element) => element.id == storageId);
                if (tempInfo.toolKitList!.isNotEmpty) {
                  for (var element in tempInfo.toolKitList ?? []) {
                    toolKitList.add(element);
                  }
                }
              });
            },
            child: AnimatedContainer(
              alignment: Alignment.center,
              margin: const EdgeInsets.only(left: 16),
              width: 68,
              decoration: BoxDecoration(
                  borderRadius: const BorderRadius.all(Radius.circular(15)),
                  shape: BoxShape.rectangle,
                  border: Border.all(
                      color: AppTheme.appTheme.grandientColorEnd(), width: 1.5),
                  color: storageName == selectStorage
                      ? AppTheme.appTheme.grandientColorEnd()
                      : AppTheme.appTheme.cardBackgroundColor()),
              duration: const Duration(milliseconds: 300),
              child: Text(
                storageName,
                style: AppTheme.appTheme.headline1(
                    textColor: storageName == selectStorage
                        ? AppTheme.appTheme.cardBackgroundColor()
                        : AppTheme.appTheme.grandientColorEnd(),
                    fontWeight: FontWeight.w200,
                    fontSize: 15),
              ),
            ),
          );
        },
        itemCount: keyValueList.length,
        scrollDirection: Axis.horizontal,
      ),
    );
  }

  List<String> selectToolKit = [];
  List<ToolKit> toolKitList = [];
  Widget toolKitView(List<ToolKit> keyValueList) {
    return Container(
      margin: const EdgeInsets.only(top: 6),
      height: 48,
      child: ListView.builder(
        padding: const EdgeInsets.only(left: 16, right: 16, bottom: 8),
        itemBuilder: (context, index) {
          String storageName = keyValueList[index].toolKitName;
          return GestureDetector(
            onTap: () {
              setState(() {
                if (selectToolKit.contains(storageName)) {
                  selectToolKit.remove(storageName);
                } else {
                  selectToolKit.add(storageName);
                }
                if (selectToolKitList.contains(keyValueList[index])) {
                  selectToolKitList.remove(keyValueList[index]);
                } else {
                  selectToolKitList.add(keyValueList[index]);
                }
              });
            },
            child: AnimatedContainer(
              alignment: Alignment.center,
              margin: const EdgeInsets.only(left: 16),
              width: 68,
              decoration: BoxDecoration(
                  borderRadius: const BorderRadius.all(Radius.circular(15)),
                  shape: BoxShape.rectangle,
                  border: Border.all(
                      color: AppTheme.appTheme.grandientColorEnd(), width: 1.5),
                  color: selectToolKit.contains(storageName)
                      ? AppTheme.appTheme.grandientColorEnd()
                      : AppTheme.appTheme.cardBackgroundColor()),
              duration: const Duration(milliseconds: 300),
              child: Text(
                storageName,
                style: AppTheme.appTheme.headline1(
                    textColor: selectToolKit.contains(storageName)
                        ? AppTheme.appTheme.cardBackgroundColor()
                        : AppTheme.appTheme.grandientColorEnd(),
                    fontWeight: FontWeight.w200,
                    fontSize: 15),
              ),
            ),
          );
        },
        itemCount: keyValueList.length,
        scrollDirection: Axis.horizontal,
      ),
    );
  }

  String selectToolInfo = '';

  Widget toolKitSelectView(List<ToolKit> keyValueList) {
    return Container(
      margin: const EdgeInsets.only(top: 6),
      height: 48,
      child: ListView.builder(
        padding: const EdgeInsets.only(left: 16, right: 16, bottom: 8),
        itemBuilder: (context, index) {
          String toolKitName = keyValueList[index].toolKitName;
          return GestureDetector(
            onTap: () {
              setState(() {
                if (selectStorage != selectToolInfo) {
                  tempList = [];
                  selectGPO = 0;
                  selectGPI = 0;
                }
                selectToolInfo = toolKitName;
                selectGPO = keyValueList[index].gpo;
                selectGPI = keyValueList[index].gpi;
                if (selectGPO > 0) {
                  gpoMap.putIfAbsent(selectToolInfo, () => selectGPO);
                }
                if (selectGPI > 0) {
                  gpiMap.putIfAbsent(selectToolInfo, () => selectGPI);
                }
              });
            },
            child: AnimatedContainer(
              alignment: Alignment.center,
              margin: const EdgeInsets.only(left: 16),
              width: 68,
              decoration: BoxDecoration(
                  borderRadius: const BorderRadius.all(Radius.circular(15)),
                  shape: BoxShape.rectangle,
                  border: Border.all(
                      color: AppTheme.appTheme.grandientColorEnd(), width: 1.5),
                  color: selectToolInfo == toolKitName
                      ? AppTheme.appTheme.grandientColorEnd()
                      : AppTheme.appTheme.cardBackgroundColor()),
              duration: const Duration(milliseconds: 300),
              child: Text(
                toolKitName,
                style: AppTheme.appTheme.headline1(
                    textColor: selectToolInfo == toolKitName
                        ? AppTheme.appTheme.cardBackgroundColor()
                        : AppTheme.appTheme.grandientColorEnd(),
                    fontWeight: FontWeight.w200,
                    fontSize: 15),
              ),
            ),
          );
        },
        itemCount: keyValueList.length,
        scrollDirection: Axis.horizontal,
      ),
    );
  }

  List<String> tempList = [];
  int selectGPO = 0;
  int selectGPI = 0;

  Widget antennaSelectView(List<int> keyValueList) {
    if (antennaMap.containsKey(selectToolInfo)) {
      tempList = antennaMap[selectToolInfo] ?? [];
    }
    return Container(
      margin: const EdgeInsets.only(top: 6),
      height: 48,
      child: ListView.builder(
        padding: const EdgeInsets.only(left: 16, right: 16, bottom: 8),
        itemBuilder: (context, index) {
          String storageName = keyValueList[index].toString();
          return GestureDetector(
            onTap: () {
              setState(() {
                if (tempList.contains(storageName)) {
                  tempList.remove(storageName);
                } else {
                  tempList.add(storageName);
                }
                List<String> tempItem = [];
                for (var element in tempList) {
                  tempItem.add(element);
                }
                antennaMap[selectToolInfo] = tempItem;
              });
            },
            child: AnimatedContainer(
              alignment: Alignment.center,
              margin: const EdgeInsets.only(left: 16),
              width: 68,
              decoration: BoxDecoration(
                  borderRadius: const BorderRadius.all(Radius.circular(15)),
                  shape: BoxShape.rectangle,
                  border: Border.all(
                      color: AppTheme.appTheme.grandientColorEnd(), width: 1.5),
                  color: tempList.contains(storageName)
                      ? AppTheme.appTheme.grandientColorEnd()
                      : AppTheme.appTheme.cardBackgroundColor()),
              child: Text(
                storageName,
                style: AppTheme.appTheme.headline1(
                    textColor: tempList.contains(storageName)
                        ? AppTheme.appTheme.cardBackgroundColor()
                        : AppTheme.appTheme.grandientColorEnd(),
                    fontWeight: FontWeight.w200,
                    fontSize: 15),
              ),
              duration: const Duration(milliseconds: 300),
            ),
          );
        },
        itemCount: antennaPortList.length,
        scrollDirection: Axis.horizontal,
      ),
    );
  }

  Map<String, int> gpoMap = {};
  Map<String, int> gpiMap = {};
  Widget gpoSelectView(List<int> gpoList) {
    return Container(
      margin: const EdgeInsets.only(top: 6),
      height: 48,
      child: ListView.builder(
        padding: const EdgeInsets.only(left: 16, right: 16, bottom: 8),
        itemBuilder: (context, index) {
          int currentGpo = gpoList[index];
          return GestureDetector(
            onTap: () {
              setState(() {
                gpoMap[selectToolInfo] = currentGpo;
                selectGPO = currentGpo;
              });
            },
            child: AnimatedContainer(
              alignment: Alignment.center,
              margin: const EdgeInsets.only(left: 16),
              width: 68,
              decoration: BoxDecoration(
                  borderRadius: const BorderRadius.all(Radius.circular(15)),
                  shape: BoxShape.rectangle,
                  border: Border.all(
                      color: AppTheme.appTheme.grandientColorEnd(), width: 1.5),
                  color: selectGPO == currentGpo
                      ? AppTheme.appTheme.grandientColorEnd()
                      : AppTheme.appTheme.cardBackgroundColor()),
              child: Text(
                'GPO$currentGpo',
                style: AppTheme.appTheme.headline1(
                    textColor: selectGPO == currentGpo
                        ? AppTheme.appTheme.cardBackgroundColor()
                        : AppTheme.appTheme.grandientColorEnd(),
                    fontWeight: FontWeight.w200,
                    fontSize: 15),
              ),
              duration: const Duration(milliseconds: 300),
            ),
          );
        },
        itemCount: gpoList.length,
        scrollDirection: Axis.horizontal,
      ),
    );
  }

  Widget gpiSelectView(List<int> gpoList) {
    return Container(
      margin: const EdgeInsets.only(top: 6),
      height: 48,
      child: ListView.builder(
        padding: const EdgeInsets.only(left: 16, right: 16, bottom: 8),
        itemBuilder: (context, index) {
          int currentGpi = gpoList[index];
          return GestureDetector(
            onTap: () {
              setState(() {
                gpiMap[selectToolInfo] = currentGpi;
                selectGPI = currentGpi;
              });
            },
            child: AnimatedContainer(
              alignment: Alignment.center,
              margin: const EdgeInsets.only(left: 16),
              width: 68,
              decoration: BoxDecoration(
                  borderRadius: const BorderRadius.all(Radius.circular(15)),
                  shape: BoxShape.rectangle,
                  border: Border.all(
                      color: AppTheme.appTheme.grandientColorEnd(), width: 1.5),
                  color: selectGPI == currentGpi
                      ? AppTheme.appTheme.grandientColorEnd()
                      : AppTheme.appTheme.cardBackgroundColor()),
              child: Text(
                'GPI$currentGpi',
                style: AppTheme.appTheme.headline1(
                    textColor: selectGPI == currentGpi
                        ? AppTheme.appTheme.cardBackgroundColor()
                        : AppTheme.appTheme.grandientColorEnd(),
                    fontWeight: FontWeight.w200,
                    fontSize: 15),
              ),
              duration: const Duration(milliseconds: 300),
            ),
          );
        },
        itemCount: gpoList.length,
        scrollDirection: Axis.horizontal,
      ),
    );
  }
}
